package com.xaiojimao.gr_common.Utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtils {
    private static final long EXPIRATION_TIME = 5 * 24 * 60 * 60 * 1000;
    private static final String SECRET_KEY = "xiaojimao";

    public static String getToken(Map<String, Object> userInfo) {
        Date now = new Date();
        String token = Jwts.builder()
                .addClaims(userInfo)
                .setExpiration(new Date(now.getTime() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
        return token;
    }

    public static String getTokenInfo(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        return claims.get("userId").toString();
    }

    public static boolean isTokenValid(String token) {
        try {
            getTokenInfo(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
